package com.startupwebapp.dao.hibernate;

import java.util.List;

import org.apache.commons.beanutils.converters.IntegerConverter;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.startupwebapp.core.domain.users.Person;
import com.startupwebapp.dao.PersonDAO;

@Repository("personDAO")
public class PersonDAOImpl extends
		GenericDAOSpringHibernateImpl<Person, Integer> implements PersonDAO {

	// property constants
	public static final String FIRST_NAME = "firstName";
	public static final String LAST_NAME = "lastName";
	public static final String ACTIVE = "active";
	public static final String EMAIL = "email";
	public static final String LOGIN = "login";

	@Autowired
	IntegerConverter integerConverter;

	public List<Person> findByFirstName(Object firstName) {
		return findByProperty(FIRST_NAME, firstName);
	}

	public List<Person> findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public Person findByLogin(Object login) {
		List<Person> personList = null;
		Person person = null;
		personList = findByProperty(LOGIN, login);

		if ((personList != null) && (personList.size() > 0)) {
			person = personList.get(0);
		}
		return person;
	}

	public List<Person> findByLastName(Object lastName) {
		return findByProperty(LAST_NAME, lastName);
	}

	public List<Person> findByActive(Object active) {
		return findByProperty(ACTIVE, active);
	}

	@SuppressWarnings("unchecked")
	public List<Person> find(boolean state) {
		int activeState = (Integer) integerConverter.convert(Integer.class,
				state);
		Query query = getSession().createQuery(
				"from Person p where p.active=:state").setInteger("state",
				activeState);
		return query.list();
	}

	public int countAll() {
		Query query = getSession().createQuery("select count(p) from Person p");
		return executeCount(query);
	}

	private int executeCount(Query query) {
		Long size = (Long) query.uniqueResult();
		return size.intValue();
	}

	public int count(boolean state) {
		int stateValue = (Integer) integerConverter.convert(Integer.class,
				state);
		Query query = getSession().createQuery(
				"select count(p) from Person p where p.active=:state")
				.setInteger("state", stateValue);
		return executeCount(query);
	}

	

}